package future;

import org.junit.Test;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static future.FutureDemo.delay;

/**
 * @author lilingzhi
 * @since 2022/12/30 17:01
 */
public class CompletableFutureDemo {

    @Test
    public void test() throws ExecutionException, InterruptedException {
        LocalDateTime start = LocalDateTime.now();
        CompletableFuture<Double> future = extracted();
        CompletableFuture<Double> thenApply = future.thenApplyAsync(this::extracted2);
        delay();
        delay();
        System.out.println(thenApply.get());
        LocalDateTime end = LocalDateTime.now();
        Duration between = Duration.between(start, end);
        double v = between.toMillis() / 1_000D;
        System.out.println(v);
    }

    private Double extracted2(Double d) {
        delay();
        return ++d;
    }

    private CompletableFuture<Double> extracted() throws InterruptedException, ExecutionException {
        CompletableFuture<Double> future = CompletableFuture.supplyAsync(this::cal);
        return future;
    }

    private Double cal() {
        delay();
        double v = new Random().nextDouble();
        System.out.println(v);
        return v;
    }


}
